<template>
	<view class="container padding">
        <checkbox-group @change="changeCheckbox">
		<view class="card">
			<view class="alert-list" v-for="alert in tableData" :key="alert.deviceId" @click="markAsRead(alert)">
				<view class="alert-item" :class="{ 'unread': alert.state === '0' }">
				  <!-- 上部内容：左侧图标和右侧设备信息 -->
				  <view class="alert-top">
					<!-- 左侧图标 -->
					<view class="alert-left">
					  <view class="iconfont alert-icon">&#xe666;</view>
					</view>
					<!-- 右侧设备信息 -->
					<view class="alert-right">
					  <!-- 第一行：单位名称 -->
					  <view class="alert-info">
						<text class="device-name">{{ alert.clientName }}</text>
						<text class="user-name">{{ alert.username || "管理员" }}</text>
					  </view>
					  <!-- 分割线 -->
					  <view class="divider"></view>
					  <!-- 第二行：发布时间 -->
					  <text class="alert-time">
						  <text class="desc-title">发布时间：</text>{{ alert.createTime }}
					  </text>
					  <!-- 第三行：消息类型 -->
					  <text class="alert-type">
						  <text class="desc-title">消息类型：</text>{{ alert.type=="1"?"通知":"公告" }}
					  </text>
					</view>
				  </view>
				  <!-- 分割线 -->
				  <view class="divider"></view>
				  <view class="single-line">
                      <view class="alert-info">
                          <text class="device-name">{{ alert.content }}</text>
                          <checkbox v-if="alert.state === '0'" class="user-name" :value="alert.id" :checked="checkedArr.includes(alert.id)" @change="changeCheckbox"></checkbox>
                      </view>
				  </view>
				</view>
			</view>
		</view>
        </checkbox-group>
	</view>
</template>

<script>
	import request from '@/util/request';
	export default {
        data() {
			return {
				searchName: '',
				tableData: [],
                unReadTableData: [],
				pageNum: 1,
				pageSize: 10,
				total: 0,
                allChecked: false,
                checkedArr:[],
			}
		},
		mounted() {
			this.load()
		},
		onShow() {
			this.sortAlerts(); // 排序
		},
		onPullDownRefresh() {
			this.pageNum=1;
			this.pageSize=10;
			this.load()
			uni.stopPullDownRefresh();
		},
		onReachBottom() { //触底事件
			if (this.pageNum * this.pageSize >= this.total) {
				uni.showToast({
					title: '没有更多数据了',
					icon: 'none',
					duration: 1000
				});
			} else {
				uni.showLoading({
					title: '加载中'
				});
				this.pageSize+=10
				this.load()
				setTimeout(() => {
					uni.hideLoading()
				}, 500)
			}
		},
        onNavigationBarButtonTap(val) {
            console.log(val)
            if(val.text === "全选"){
                this.allChecked = this.allChecked?false:true
                console.log(this.allChecked)
                this.allChoose()
            } else {
                this.readAll()
            }
        },
		methods: {
            // 多选复选框改变事件
            changeCheckbox(e){
                this.checkedArr = e.detail.value
                // 如果选择的数组中有值，并且长度等于列表的长度，就是全选
                if(this.checkedArr.length > 0 && this.checkedArr.length === this.unReadTableData.length) {
                    this.allChecked=true;
                }else{
                    this.allChecked=false;
                }
            },
            // 全选事件
            allChoose(e){
                // 全选
                if(this.allChecked === true){
                    for(let item of this.unReadTableData){
                        let itemVal=item.id;
                        if(!this.checkedArr.includes(itemVal)){
                            this.checkedArr.push(itemVal);
                        }
                    }
                }else{
                    this.checkedArr=[];
                }
            },
            readAll() {
                console.log(this.checkedArr)
                if(this.checkedArr.length > 0) {
                    request.get("/announce/updateAll?announceIds=" + this.checkedArr).then(res => {
                        if (res.code === '200') {
                            uni.showToast({
                                title: "成功",
                                icon:'success',
                                duration: 2000
                            });
                            this.load()
                            this.checkedArr = []
                        } else {
                            uni.showToast({
                                title: "失败",
                                icon:'error',
                                duration: 2000
                            });
                        }
                    })
                }
            },
			// 跳转并标记为已读
			markAsRead(notice) {
				if (notice.state === '0') {
					notice.state = '1'; // 设置为已读
					this.updateReadState(notice); // 同步到后端
				}
				this.naviTo('/pages/notice/detial', notice);
			},
			// 更新已读状态到后端
			updateReadState(notice) {
				request.post('/announce/edit',notice).then(res => {
					if (res.code === '200') {
						console.log('标记成功');
					}
				});
			},
			naviTo(url,item){
				uni.navigateTo({
					url:url+"?data="+JSON.stringify(item)
				})
			},
			load(){
				let userId = this.$store.state.userInfo.id;
				let level = this.$store.state.userInfo.level;
				let organizationId = this.$store.state.userInfo.organization;
				let isAllClient = this.$store.state.userInfo.isAllClient;
				let clientIds;
				if (isAllClient === "1") {
					clientIds = this.$store.state.userInfo.clientIds;
				} else {
					clientIds = [];
				}
				request.get("/announce/findByUserId?pageNum=" + this.pageNum + "&pageSize=" + this.pageSize + "&keyWord=" +
						this.searchName + "&level=" + level + "&organizationId=" + organizationId + "&isAllClient=" + isAllClient + "&clientIds=" + clientIds + "&userId=" + userId).then(res => {
					if (res.code === '200') {
						for (let key in res.data) {
							if (key === "record") {
								this.tableData = res.data[key];
                                for (let i = 0; i < this.tableData.length; i++) {
                                    if(this.tableData[i].state === '0') {
                                        this.unReadTableData.push(this.tableData[i])
                                    }
                                }
							} else if (key === "total") {
								this.total = res.data[key];
							}
						}
						this.sortAlerts(); // 排序
					} else {
						uni.showToast({
							title: "失败",
							icon:'error',
							duration: 2000
						});
					}
				})
			},
			// 排序方法：先按未读已读，再按时间从新到旧
			sortAlerts() {
				this.tableData.sort((a, b) => {
					if (a.state === b.state) {
						// 同为已读或未读，按时间排序（假设 createTime 为 ISO 时间字符串）
						return new Date(b.createTime) - new Date(a.createTime);
					}
					return a.state - b.state; // 未读 (state=0) 优先
				});
			},
		}
	}
</script>

<style scoped>
.container{

}
.card{
	border-radius: 8px;
	height: 100px;
	background-color: #fff;
}
.alert-list {
  margin-top: 20rpx;
}
.desc-title{
	color: var(--gray-color);
}
.alert-item {
  border-left: 5px solid #00c200; /* 左侧标记为蓝色 */
  background-color: #f8f8f8;
  padding: 20rpx;
  margin: 10rpx 0;
  border-radius: 10rpx;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 上部：左右结构 */
.alert-top {
  display: flex;
  align-items: center;
}

.alert-left {
  display: flex;
  align-items: center;
  margin-right: 10px;
}

.alert-icon {
  color: var(--blue-color);
  font-size: 40px;
}

.alert-right {
  flex: 1;
  display: flex;
  flex-direction: column;
}
.alert-right1 {
    display: flex;
    align-items: center;
    margin-right: 10px;
}
/* 第一行：设备名称和设备号 */
.alert-info {
  display: flex;
  justify-content: space-between;
}

.device-name,.user-name {
  font-size: 15px;
  color: #333;
}

/* 第二行：报警描述 */
.alert-time {
  color: var(--gray-b-color);
  font-size: 14px;
  margin: 5rpx 0;
}

/* 第三行：报警时间 */
.alert-type {
  color: var(--gray-b-color);
  font-size: 14px;
  margin-top: 4rpx;
}

/* 分割线样式 */
.divider {
  height: 1px;
  background-color: #e0e0e0;
  margin: 10px 0;
}
.single-line {
  overflow: hidden;       /* 隐藏超出部分 */
  white-space: nowrap;    /* 强制单行显示 */
  text-overflow: ellipsis; /* 溢出部分显示省略号 */
  display: block;         /* 确保块级显示 */
  font-size: 14px;        /* 根据需求设置字体大小 */
  color: #333;            /* 文本颜色 */
}
.unread {
  background-color: #fff; /* 背景色标记为未读 */
  border-left: 5px solid #c80000; /* 左侧标记为蓝色 */
}

</style>
